﻿using Microsoft.Owin;
using Microsoft.Owin.Logging;
using Microsoft.Owin.Security.DataHandler;
using Microsoft.Owin.Security.DataProtection;
using Microsoft.Owin.Security.Infrastructure;
using Microsoft.Owin.Security.OAuth;
using Newtonsoft.Json;
using Owin;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TongTongMall.Logging;
using TongTongMall.Oauth2._0.Owin.Context;
using TongTongMall.UI;
using TongTongMall.WebApi.Models;

namespace TongTongMall.Oauth2._0.Client
{
    public class OAuthAuthorizationServerMiddlewareExtended : OAuthAuthorizationServerMiddleware
    {
        private readonly ILogger _logger;

        public OAuthAuthorizationServerMiddlewareExtended(OwinMiddleware next, IAppBuilder app, OAuthAuthorizationServerOptions options) : base(next, app, options)
        {
            _logger = app.CreateLogger<OAuthAuthorizationServerMiddlewareExtended>();
        }

        public override async Task Invoke(IOwinContext context)
        {
            try
            {
                await base.Invoke(context);
            }
            catch (UserFriendlyException ex)
            {
                LogHelper.LogException(ex);
                var errorInfo = ErrorInfoBuilder.Instance.BuildForException(ex.GetBaseException());
                await context.JsonResult(new { code = errorInfo.Code, message = errorInfo.Message });
            }
        }
    }
}
